package com.entidades.dao;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

/**
 *
 * @author Ricardo
 */
public abstract class DaoBasico {

    public DaoBasico() {
    }

    public static Object merge(Object o, EntityManager em, UserTransaction utx) {
        try {
            utx.begin();
            em.joinTransaction();
            o = em.merge(o);
            utx.commit();

        } catch (Exception ex) {
            Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex);
            try {
                utx.rollback();
            } catch (Exception ex1) {
                Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }

        return o;

    }

    public static void persist(Object o, EntityManager em, UserTransaction utx) {
        try {
            utx.begin();
            em.joinTransaction();
            em.persist(o);
            utx.commit();

        } catch (Exception ex) {
            Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex);
            try {
                utx.rollback();
            } catch (Exception ex1) {
                Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }

    }

    public static void remove(Object o, EntityManager em, UserTransaction utx) {

        try {
            utx.begin();
            em.joinTransaction();
            em.remove(em.merge(o));
            utx.commit();

        } catch (Exception ex) {
            Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex);
            try {
                utx.rollback();
            } catch (Exception ex1) {
                Logger.getLogger(DaoBasico.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }


    }

    public static Query createQuery(String string) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SMSChattyPU");
        EntityManager em = emf.createEntityManager();

        return em.createQuery(string);

    }
}
